<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;

class Brand extends Allow
{
    public function getindex()
    {
        // 获取品牌列表
        $brand=Db::table("brand")->select();
        // var_dump($brand);
    	//加载品牌列表模板
    	return $this->fetch("Brand/index",['brand'=>$brand]);
    }

    // //添加
    public function getadd(){
        //加载品牌添加模板
        return $this->fetch("Brand/add");
    }

    // //执行添加
    public function postinsert(){
        // echo '1';
        $request=request();
        //获取品牌名称和品牌状态
        $row=$request->only(['brand','status']);
        // var_dump(!empty($row['brand']));exit;
        // 判断品牌是否重复添加
        if(Db::table("brand")->where('brand',"{$row['brand']}")->select()){
            $this->error("该品牌已存在","/adminbrand/add");exit;
        }
        if(empty($row['brand'])){
            $this->error("品牌名称不能为空,请重新添加");exit;
        }else{
            if(Db::table("brand")->insert($row)){
                $this->success("品牌添加成功","/adminbrand/index");
            }else{
                $this->error("品牌添加失败","/adminbrand/add");
            }
        }
    }
    //删除
    public function getdelete(){
        $request=request();
        //获取id
        $id=$request->param('id');
        if(Db::table('brand')->where('id',"{$id}")->delete()){
            $this->success("删除成功","/adminbrand/index");
        }else{
            $this->error("删除失败","/adminbrand/index");
        }
    }
    //变换状态
    public  function getstatus(){
        $request=request();
        //获取id
        $data=$request->only(['id','status']);
        $id = $data['id'];
        $status = $data['status'];
        //判断连接状态
        if($status=='0'){
            $status='1';
        }else{
            $status='0';
        }
        // var_dump($id);
        // var_dump($status);
        if(Db::execute("update brand set status='{$status}' where id='{$id}'")){
            $this->redirect("/adminbrand/index");
        }else{
            $this->error("/adminbrand/index");
        }
    }

    //编辑
    public function getedit(){
        $request=request();
        //获取id
        $id=$request->param('id');
        // var_dump($id);
        $result = Db::query("select * from brand where id={$id}");
        $res = $result['0'];
        return $this->fetch("Brand/edit",['res'=>$res]);
    }
    //执行编辑操作
    public  function postupdate(){
        // echo '1';exit;
        $request=request();
        //获取id
        $data=$request->only(['id','brand','status']);
        // var_dump($data);
        $id = $data['id'];
        $brand= $data['brand'];
        $status = $data['status'];
        if($brand){
            //执行更新
            if(Db::execute("update brand set brand='{$brand}',status='{$status}' where id='{$id}'")){
                $this->success("更新成功","/adminbrand/index");
            }else{
                $this->error("更新失败","/adminbrand/index");
            }
        }else{$this->error("商品名称不能为空,请重新编辑");}
    }
}
